package com.test.jms.demo;

import java.io.IOException;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer {

	public static void main(String[] args) throws IOException {

		Session session = null;
		MessageConsumer consumer = null;
		Connection connection = null;

		try {
			String jmsProviderAddress = "tcp://0.0.0.0:61616";// 地址

			ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
					jmsProviderAddress);// 连接器

			connection = connectionFactory.createConnection();// 创建连接

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);// 打开会话

			String destinationName = "demoQueue";

			Destination dest = session.createQueue(destinationName);// 消息目的地

			consumer = session.createConsumer(dest);

		


			MessageListener listener = new MessageListener() {

				public void onMessage(Message message) {
					// TODO Auto-generated method stub
					System.out.println("get: " + message);
				}
			};
			
			consumer.setMessageListener(listener);
			
			connection.start();
			System.out.println("连接建立……");

			System.in.read();
//			while (true) {
//				Message message = consumer.receive();
//
//				TextMessage textMessage = (TextMessage) message;
//
//				String text = textMessage.getText();
//
//				System.out.println("从ActiveMQ取回一条消息: " + text);
//			}
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			try {
				consumer.close();
				session.close();
				connection.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}

	}

}
